/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.FaceBaseDto;
import com.yami.shop.bean.app.dto.FaceDesignDto;
import com.yami.shop.bean.app.dto.FaceDraftDto;
import com.yami.shop.bean.model.FaceBase;
import com.yami.shop.bean.model.FaceDesign;
import com.yami.shop.bean.model.FaceDraft;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.FaceBaseService;
import com.yami.shop.service.FaceDesignService;
import com.yami.shop.service.FaceDraftService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 设计稿接口
 * @author AI Assistant
 */
@RestController
@RequestMapping("/p/faceDesign")
@Tag(name = "设计稿接口")
public class FaceDesignController {

    @Autowired
    private FaceDesignService faceDesignService;

    @Autowired
    private FaceBaseService faceBaseService;

    @Autowired
    private FaceDraftService faceDraftService;

    /**
     * 获取设计稿列表（分页）
     */
    @GetMapping("/page")
    @Operation(summary = "获取设计稿列表" , description = "分页获取设计稿列表")
    @Parameter(name = "status", description = "状态（1:草稿, 2:已完成, 3:已发布）", required = false)
    public ServerResponseEntity<IPage<FaceDesignDto>> page(
            @RequestParam(value = "status", required = false) Integer status,
            PageParam<FaceDesign> page) {
        String userId = SecurityUtils.getUser().getUserId();

        IPage<FaceDesign> faceDesignPage = faceDesignService.pageByUserIdAndStatus(page, userId, status);
        IPage<FaceDesignDto> faceDesignDtoPage = faceDesignPage.convert(faceDesign -> {
            FaceDesignDto faceDesignDto = BeanUtil.copyProperties(faceDesign, FaceDesignDto.class);

            // 手动设置featureConfig字段，因为BeanUtil.copyProperties无法处理JSON序列化
            faceDesignDto.setFeatureConfig(faceDesign.getFeatureConfig());

            // 加载关联的人脸底图信息
            if (faceDesign.getFaceBaseId() != null) {
                FaceBase faceBase = faceBaseService.getById(faceDesign.getFaceBaseId());
                if (faceBase != null) {
                    FaceBaseDto faceBaseDto = BeanUtil.copyProperties(faceBase, FaceBaseDto.class);
                    faceDesignDto.setFaceBase(faceBaseDto);
                }
            }

            // 加载关联的草稿信息
            if (faceDesign.getDraftId() != null) {
                FaceDraft faceDraft = faceDraftService.getById(faceDesign.getDraftId());
                if (faceDraft != null) {
                    FaceDraftDto faceDraftDto = BeanUtil.copyProperties(faceDraft, FaceDraftDto.class);
                    faceDesignDto.setFaceDraft(faceDraftDto);
                }
            }

            return faceDesignDto;
        });

        return ServerResponseEntity.success(faceDesignDtoPage);
    }

    /**
     * 获取设计稿列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取设计稿列表" , description = "获取设计稿列表")
    @Parameter(name = "status", description = "状态（1:草稿, 2:已完成, 3:已发布）", required = false)
    public ServerResponseEntity<List<FaceDesignDto>> list(
            @RequestParam(value = "status", required = false) Integer status) {
        String userId = SecurityUtils.getUser().getUserId();
        List<FaceDesign> faceDesignList = faceDesignService.listByUserIdAndStatus(userId, status);
        List<FaceDesignDto> faceDesignDtoList = faceDesignList.stream().map(faceDesign -> {
            FaceDesignDto faceDesignDto = BeanUtil.copyProperties(faceDesign, FaceDesignDto.class);

            // 手动设置featureConfig字段，因为BeanUtil.copyProperties无法处理JSON序列化
            faceDesignDto.setFeatureConfig(faceDesign.getFeatureConfig());

            // 加载关联的人脸底图信息
            if (faceDesign.getFaceBaseId() != null) {
                FaceBase faceBase = faceBaseService.getById(faceDesign.getFaceBaseId());
                if (faceBase != null) {
                    FaceBaseDto faceBaseDto = BeanUtil.copyProperties(faceBase, FaceBaseDto.class);
                    faceDesignDto.setFaceBase(faceBaseDto);
                }
            }

            // 加载关联的草稿信息
            if (faceDesign.getDraftId() != null) {
                FaceDraft faceDraft = faceDraftService.getById(faceDesign.getDraftId());
                if (faceDraft != null) {
                    FaceDraftDto faceDraftDto = BeanUtil.copyProperties(faceDraft, FaceDraftDto.class);
                    faceDesignDto.setFaceDraft(faceDraftDto);
                }
            }

            return faceDesignDto;
        }).collect(Collectors.toList());

        return ServerResponseEntity.success(faceDesignDtoList);
    }

    /**
     * 获取设计稿详情
     */
    @GetMapping("/info")
    @Operation(summary = "获取设计稿详情" , description = "根据设计稿ID获取详情")
    @Parameter(name = "designId", description = "设计稿ID", required = true)
    public ServerResponseEntity<FaceDesignDto> info(@RequestParam("designId") Long designId) {

        String userId = SecurityUtils.getUser().getUserId();
        FaceDesign faceDesign = faceDesignService.getById(designId);
        if (faceDesign == null) {
            return ServerResponseEntity.success();
        }

        // 校验用户权限
        if (!faceDesign.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限查看该设计稿");
        }

        FaceDesignDto faceDesignDto = BeanUtil.copyProperties(faceDesign, FaceDesignDto.class);

        // 手动设置featureConfig字段，因为BeanUtil.copyProperties无法处理JSON序列化
        faceDesignDto.setFeatureConfig(faceDesign.getFeatureConfig());

        // 加载关联的人脸底图信息
        if (faceDesign.getFaceBaseId() != null) {
            FaceBase faceBase = faceBaseService.getById(faceDesign.getFaceBaseId());
            if (faceBase != null) {
                FaceBaseDto faceBaseDto = BeanUtil.copyProperties(faceBase, FaceBaseDto.class);
                faceDesignDto.setFaceBase(faceBaseDto);
            }
        }

        // 加载关联的草稿信息
        if (faceDesign.getDraftId() != null) {
            FaceDraft faceDraft = faceDraftService.getById(faceDesign.getDraftId());
            if (faceDraft != null) {
                FaceDraftDto faceDraftDto = BeanUtil.copyProperties(faceDraft, FaceDraftDto.class);
                faceDesignDto.setFaceDraft(faceDraftDto);
            }
        }

        return ServerResponseEntity.success(faceDesignDto);
    }

    /**
     * 根据草稿ID获取设计稿
     */
    @GetMapping("/infoByDraftId")
    @Operation(summary = "根据草稿ID获取设计稿" , description = "根据草稿ID获取设计稿")
    @Parameter(name = "draftId", description = "草稿ID", required = true)
    public ServerResponseEntity<FaceDesignDto> infoByDraftId(@RequestParam("draftId") Long draftId) {

        String userId = SecurityUtils.getUser().getUserId();
        FaceDesign faceDesign = faceDesignService.getByDraftId(draftId);
        if (faceDesign == null) {
            return ServerResponseEntity.success();
        }

        // 校验用户权限
        if (!faceDesign.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限查看该设计稿");
        }

        FaceDesignDto faceDesignDto = BeanUtil.copyProperties(faceDesign, FaceDesignDto.class);

        // 手动设置featureConfig字段，因为BeanUtil.copyProperties无法处理JSON序列化
        faceDesignDto.setFeatureConfig(faceDesign.getFeatureConfig());

        // 加载关联的人脸底图信息
        if (faceDesign.getFaceBaseId() != null) {
            FaceBase faceBase = faceBaseService.getById(faceDesign.getFaceBaseId());
            if (faceBase != null) {
                FaceBaseDto faceBaseDto = BeanUtil.copyProperties(faceBase, FaceBaseDto.class);
                faceDesignDto.setFaceBase(faceBaseDto);
            }
        }

        // 加载关联的草稿信息
        if (faceDesign.getDraftId() != null) {
            FaceDraft faceDraft = faceDraftService.getById(faceDesign.getDraftId());
            if (faceDraft != null) {
                FaceDraftDto faceDraftDto = BeanUtil.copyProperties(faceDraft, FaceDraftDto.class);
                faceDesignDto.setFaceDraft(faceDraftDto);
            }
        }

        return ServerResponseEntity.success(faceDesignDto);
    }

    /**
     * 创建设计稿
     */
    @PostMapping("/save")
    @Operation(summary = "创建设计稿" , description = "创建新的设计稿")
    public ServerResponseEntity<Void> save(@RequestBody FaceDesignDto faceDesignDto) {
        String userId = SecurityUtils.getUser().getUserId();
        String radomString = UUID.randomUUID().toString();
        faceDesignDto.setDraftId(radomString);
        faceDesignDto.setUserId(userId);
        FaceDesign faceDesign = BeanUtil.copyProperties(faceDesignDto, FaceDesign.class);
        faceDesign.setCreateTime(new Date());
        faceDesign.setUpdateTime(new Date());
        faceDesignService.saveFaceDesign(faceDesign);

        return ServerResponseEntity.success();
    }

    /**
     * 更新设计稿
     */
    @PutMapping("/update")
    @Operation(summary = "更新设计稿" , description = "更新设计稿信息")
    public ServerResponseEntity<Void> update(@RequestBody FaceDesign faceDesign) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesign existingDesign = faceDesignService.getById(faceDesign.getDesignId());
        if (existingDesign == null) {
            return ServerResponseEntity.showFailMsg("设计稿不存在");
        }
        if (!existingDesign.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限更新该设计稿");
        }

        faceDesign.setUpdateTime(new Date());
        faceDesignService.updateFaceDesign(faceDesign);

        return ServerResponseEntity.success();
    }

    /**
     * 删除设计稿
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除设计稿" , description = "根据设计稿ID删除")
    @Parameter(name = "designId", description = "设计稿ID", required = true)
    public ServerResponseEntity<Void> delete(@RequestParam("designId") Long designId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesign existingDesign = faceDesignService.getById(designId);
        if (existingDesign == null) {
            return ServerResponseEntity.showFailMsg("设计稿不存在");
        }
        if (!existingDesign.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限删除该设计稿");
        }

        faceDesignService.removeById(designId);
        return ServerResponseEntity.success();
    }

    /**
     * 更新设计稿状态
     */
    @PutMapping("/updateStatus")
    @Operation(summary = "更新设计稿状态" , description = "更新设计稿状态")
    @Parameter(name = "designId", description = "设计稿ID", required = true)
    @Parameter(name = "status", description = "状态：0-禁用，1-启用", required = true)
    public ServerResponseEntity<Void> updateStatus(
            @RequestParam("designId") Long designId,
            @RequestParam("status") Integer status) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesign existingDesign = faceDesignService.getById(designId);
        if (existingDesign == null) {
            return ServerResponseEntity.showFailMsg("设计稿不存在");
        }
        if (!existingDesign.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限更新该设计稿状态");
        }

        FaceDesign faceDesign = new FaceDesign();
        faceDesign.setDesignId(designId);
        faceDesign.setDesignStatus(status);
        faceDesign.setUpdateTime(new Date());
        faceDesignService.updateById(faceDesign);
        return ServerResponseEntity.success();
    }

    /**
     * 统计设计稿数量
     */
    @GetMapping("/count")
    @Operation(summary = "统计设计稿数量" , description = "统计用户设计稿数量")
    @Parameter(name = "status", description = "状态（1:草稿, 2:已完成, 3:已发布）", required = false)
    public ServerResponseEntity<Integer> count(
            @RequestParam(value = "status", required = false) Integer status) {
        String userId = SecurityUtils.getUser().getUserId();

        Integer count = faceDesignService.countByUserIdAndStatus(userId, status);
        return ServerResponseEntity.success(count);
    }

    /**
     * 增加查看次数
     */
    @PutMapping("/incrementView")
    @Operation(summary = "增加查看次数" , description = "增加设计稿查看次数")
    @Parameter(name = "designId", description = "设计稿ID", required = true)
    public ServerResponseEntity<Void> incrementView(@RequestParam("designId") Long designId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesign existingDesign = faceDesignService.getById(designId);
        if (existingDesign == null) {
            return ServerResponseEntity.showFailMsg("设计稿不存在");
        }
        if (!existingDesign.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限操作该设计稿");
        }

        FaceDesign faceDesign = new FaceDesign();
        faceDesign.setDesignId(designId);
        faceDesign.setViewCount(existingDesign.getViewCount() != null ? existingDesign.getViewCount() + 1 : 1);
        faceDesign.setUpdateTime(new Date());
        faceDesignService.updateById(faceDesign);

        return ServerResponseEntity.success();
    }

    /**
     * 增加点赞次数
     */
    @PutMapping("/incrementLike")
    @Operation(summary = "增加点赞次数" , description = "增加设计稿点赞次数")
    @Parameter(name = "designId", description = "设计稿ID", required = true)
    public ServerResponseEntity<Void> incrementLike(@RequestParam("designId") Long designId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesign existingDesign = faceDesignService.getById(designId);
        if (existingDesign == null) {
            return ServerResponseEntity.showFailMsg("设计稿不存在");
        }
        if (!existingDesign.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限操作该设计稿");
        }

        FaceDesign faceDesign = new FaceDesign();
        faceDesign.setDesignId(designId);
        faceDesign.setLikeCount(existingDesign.getLikeCount() != null ? existingDesign.getLikeCount() + 1 : 1);
        faceDesign.setUpdateTime(new Date());
        faceDesignService.updateById(faceDesign);
        return ServerResponseEntity.success();
    }

    /**
     * 获取用户的设计稿列表（分页）
     */
    @GetMapping("/user/page")
    @Operation(summary = "获取用户的设计稿列表" , description = "分页获取用户的设计稿列表")
    @Parameter(name = "designStatus", description = "设计稿状态", required = false)
    @Parameter(name = "isPublic", description = "是否公开", required = false)
    public ServerResponseEntity<IPage<FaceDesignDto>> getUserDesignPage(
            @RequestParam(value = "designStatus", required = false) Integer designStatus,
            @RequestParam(value = "isPublic", required = false) Integer isPublic,
            PageParam<FaceDesign> page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<FaceDesign> faceDesignPage = faceDesignService.pageByUserIdAndStatus(page, userId, designStatus);
        IPage<FaceDesignDto> faceDesignDtoPage = faceDesignPage.convert(faceDesign -> {
            FaceDesignDto faceDesignDto = BeanUtil.copyProperties(faceDesign, FaceDesignDto.class);
            return faceDesignDto;
        });

        return ServerResponseEntity.success(faceDesignDtoPage);
    }

    /**
     * 获取公开的设计稿列表（分页）
     */
    @GetMapping("/public/page")
    @Operation(summary = "获取公开的设计稿列表" , description = "分页获取公开的设计稿列表")
    @Parameter(name = "designStatus", description = "设计稿状态", required = false)
    @Parameter(name = "sortBy", description = "排序字段", required = false)
    @Parameter(name = "sortOrder", description = "排序方式", required = false)
    public ServerResponseEntity<IPage<FaceDesignDto>> getPublicDesignPage(
            @RequestParam(value = "designStatus", required = false) Integer designStatus,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "sortOrder", required = false) String sortOrder,
            PageParam<FaceDesign> page) {

        // 这里需要实现获取公开设计稿的逻辑
        // 暂时使用现有的分页方法，后续需要根据公开状态进行过滤
        IPage<FaceDesign> faceDesignPage = faceDesignService.pageByUserIdAndStatus(page, null, designStatus);
        IPage<FaceDesignDto> faceDesignDtoPage = faceDesignPage.convert(faceDesign -> {
            FaceDesignDto faceDesignDto = BeanUtil.copyProperties(faceDesign, FaceDesignDto.class);
            return faceDesignDto;
        });

        return ServerResponseEntity.success(faceDesignDtoPage);
    }

    /**
     * 点赞设计稿
     */
    @PutMapping("/like/{designId}")
    @Operation(summary = "点赞设计稿" , description = "点赞设计稿")
    @Parameter(name = "designId", description = "设计稿ID", required = true)
    public ServerResponseEntity<Void> likeDesign(@PathVariable("designId") Long designId) {
        return incrementLike(designId);
    }

    /**
     * 取消点赞设计稿
     */
    @PutMapping("/unlike/{designId}")
    @Operation(summary = "取消点赞设计稿" , description = "取消点赞设计稿")
    @Parameter(name = "designId", description = "设计稿ID", required = true)
    public ServerResponseEntity<Void> unlikeDesign(@PathVariable("designId") Long designId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesign existingDesign = faceDesignService.getById(designId);
        if (existingDesign == null) {
            return ServerResponseEntity.showFailMsg("设计稿不存在");
        }
        if (!existingDesign.getUserId().equals(userId)) {
            return ServerResponseEntity.showFailMsg("没有权限操作该设计稿");
        }

        FaceDesign faceDesign = new FaceDesign();
        faceDesign.setDesignId(designId);
        faceDesign.setLikeCount(existingDesign.getLikeCount() != null && existingDesign.getLikeCount() > 0 ? existingDesign.getLikeCount() - 1 : 0);
        faceDesign.setUpdateTime(new Date());
        faceDesignService.updateById(faceDesign);
        return ServerResponseEntity.success();
    }

    /**
     * 复制设计稿
     */
    @PostMapping("/copy/{designId}")
    @Operation(summary = "复制设计稿" , description = "复制设计稿")
    @Parameter(name = "designId", description = "设计稿ID", required = true)
    public ServerResponseEntity<Void> copyDesign(@PathVariable("designId") Long designId) {

        String userId = SecurityUtils.getUser().getUserId();

        // 校验用户权限
        FaceDesign existingDesign = faceDesignService.getById(designId);
        if (existingDesign == null) {
            return ServerResponseEntity.showFailMsg("设计稿不存在");
        }

        // 复制设计稿
        FaceDesign newDesign = BeanUtil.copyProperties(existingDesign, FaceDesign.class);
        newDesign.setDesignId(null); // 清除ID，让数据库生成新ID
        newDesign.setUserId(userId); // 设置为当前用户
        newDesign.setDesignName(existingDesign.getDesignName() + "_副本");
        newDesign.setCreateTime(new Date());
        newDesign.setUpdateTime(new Date());
        newDesign.setViewCount(0);
        newDesign.setLikeCount(0);
        faceDesignService.saveFaceDesign(newDesign);

        return ServerResponseEntity.success();
    }
}
